<?php
namespace api\authclient\clients;

use yii\authclient\OAuth2;
use yii\web\HttpException;
use yii\authclient\OAuthToken;
use dektrium\user\clients\ClientInterface;

class Wechat extends OAuth2 implements ClientInterface
{
    /**
     * @inheritdoc
     */
    public $authUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize';
    /**
     * @inheritdoc
     */
    public $tokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token';
    /**
     * @inheritdoc
     */
    public $apiBaseUrl = 'https://api.weixin.qq.com';


    public function buildAuthUrl(array $params = [])
    {
        $defaultParams = [
            'appid' => $this->clientId,
            'redirect_uri' => $this->getReturnUrl(),
            'response_type' => 'code',
            'scope' => 'snsapi_userinfo',
        ];

        if ($this->validateAuthState) {
            $authState = $this->generateAuthState();
            $this->setState('authState', $authState);
            $defaultParams['state'] = $authState;
        }

        $url = $this->composeUrl($this->authUrl, array_merge($defaultParams, $params));
        return $url . '#wechat_redirect';
    }

    public function fetchAccessToken($authCode, array $params = [])
    {
        if ($this->validateAuthState) {
            $authState = $this->getState('authState');
            if (!isset($_REQUEST['state']) || empty($authState) || strcmp($_REQUEST['state'], $authState) !== 0) {
                throw new HttpException(400, 'Invalid auth state parameter.');
            } else {
                $this->removeState('authState');
            }
        }

        $defaultParams = [
            'appid' => $this->clientId,
            'secret' => $this->clientSecret,
            'code' => $authCode,
            'grant_type' => 'authorization_code',
            'redirect_uri' => $this->getReturnUrl(),
        ];

        $request = $this->createRequest()
            ->setMethod('GET')
            ->setUrl($this->tokenUrl)
            ->setData(array_merge($defaultParams, $params));

        $response = $this->sendRequest($request);

        $token = $this->createToken(['params' => $response]);
        $this->setAccessToken($token);

        return $token;
    }

    /**
     * @inheritdoc
     */
    protected function initUserAttributes()
    {
        $oauthToken = $this->getAccessToken();
        $defaultParams = [
            'access_token' => $oauthToken->params['access_token'],
            'openid' => $oauthToken->params['openid'],
            'lang' => 'zh-CN'
        ];
        $request = $this->createRequest()
            ->setMethod('GET')
            ->setUrl('sns/userinfo')
            ->setData($defaultParams);
        $resquest = $this->sendRequest($request);
        $resquest['id'] = $resquest['openid'];
        return $resquest;
    }

    public function getEmail()
    {
        return;
    }
    public function getUsername()
    {
        return $this->getUserAttributes()['nickname'];
    }
    /**
     * @inheritdoc
     */
    public function defaultName()
    {
        return 'wechat';
    }
    /**
     * @inheritdoc
     */
    public function defaultTitle()
    {
        return 'Wechat';
    }
}
